#include "Acceptor.h"

Acceptor::Acceptor(const string& ip, unsigned short port) 
:_sock()
,_addr(ip,port)
{}

void Acceptor::ready() {
    //绑定地址
    bind();
    //设置地址为可重用
    setReuseAddr();
    //设置端口号位可重用
    setReusePort();
    //监听
    listen();
    return;
}

void Acceptor::setReuseAddr() {
    int opt = 1;
    int ret = setsockopt(_sock.fd(),SOL_SOCKET,SO_REUSEPORT,&opt,sizeof(opt));
    if(ret == -1){
        perror("setsockopt");
        exit(1);
    }
    return;
}

void Acceptor::setReusePort() {
    int opt = 1;
    int ret = setsockopt(_sock.fd(),SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
    if(ret == -1){
        perror("setsockopt");
        exit(1);
    }
    return;
}

void Acceptor::bind() {
    int ret = ::bind(_sock.fd(),(struct sockaddr *)_addr.getInetAddressPtr(),sizeof(struct sockaddr_in));
    if(ret == -1){
        perror("bind");
        exit(1);
    }
    return;
}

void Acceptor::listen() {
    int ret = ::listen(_sock.fd(),128);
    if(-1 == ret){
        perror("listen");
        exit(1);
    }
    return;
}

int Acceptor::accept() {
    int connfd = ::accept(_sock.fd(),nullptr,nullptr);
    if(-1 == connfd){
        perror("accept");
        exit(1);
    }
    return connfd;
}

int Acceptor::fd(){
    return _sock.fd();
}

Acceptor::~Acceptor() {

}
